class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def minCameraCover(self, root: TreeNode) -> int:
        cameras=0
        paths=[]
        def addcamera(node,parent):
            paths.append((node,parent))
            nonlocal cameras
            cameras+=1
            if parent is not None:
                parent.val+=1
            node.val+=1
            if node.left is not None:
                node.left.val+=1
                addcamera(node.left,node)
            if node.right is not None:
                node.right.val+=1
                addcamera(node.right,node)
        addcamera(root,None)
        def printtree(node):
            print(node.val)
            if node.left is not None:
                printtree(node.left)
            if node.right is not None:
                printtree(node.right)
        def removecamera(node,parent):
            #printtree(root)
            nonlocal cameras
            flag=True
            if node.val<=1 or (parent is not None and parent.val<=1):
                flag=False
            if (node.left is not None and node.left.val<=1) or (node.right is not None and node.right.val<=1):
                flag=False
            if flag:
                cameras-=1
                if parent is not None:
                    parent.val-=1
                node.val-=1
                if node.left is not None:
                    node.left.val-=1
                if node.right is not None:
                    node.right.val-=1  
        paths.reverse()
        for i in paths:
            removecamera(i[0],i[1])
        return cameras